package com.android.love.ui;

import group.pals.android.lib.ui.lockpattern.LockPatternActivity;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.android.love.R;
import com.android.love.net.UriHelper;
import com.android.love.util.ActivityUtil;
import com.android.love.util.LogUtil;
import com.android.love.util.StringsUtil;
import com.android.love.view.BadgeView;
import com.android.love.view.InputPassWordDialog;
import com.android.love.view.InputPassWordDialog.CallBack;
import com.android.love.view.SelectDialog;
import com.android.love.vo.MyRequest;
import com.github.kevinsawicki.wishlist.ViewFinder;
import com.github.kevinsawicki.wishlist.ViewUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import group.pals.android.lib.ui.lockpattern.prefs.SecurityPrefs;

public class SettingActivity extends BasePageActivity {

    private ViewFinder setFinder;

    private int push;

    private InputPassWordDialog input;

    private boolean isFirstInput=true;

    private String pwd=null;

    private SelectDialog mSelectDialog;

    private BadgeView order_badge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View setView=inflater.inflate(R.layout.activity_set, null);
        setContentView(setView);
        setFinder=new ViewFinder(setView);
        process();
        setListener();
    }

    @Override
    protected void onResume() {
        mApplication.setDefaultIndex(SETTING);
        super.onResume();
        LogUtil.i(TAG, "onResume");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UmengUpdateAgent.setUpdateListener(null);
    }

    @Override
    protected void process() {
        super.process();
        SecurityPrefs.setAutoSavePattern(context, true);
        setFinder.setDrawable(R.id.iv_top_meinv, R.drawable.meinv);
        setFinder.setText(R.id.top_title, "个人中心");
        ViewUtils.setGone(setFinder.find(R.id.iv_kefu), false);
        ViewUtils.setGone(setFinder.find(R.id.iv_shuaxin), true);
        push=sp.getValue("push", 1);
        if(push == 0) {
            // 关
            setFinder.setDrawable(R.id.iv_tixing, R.drawable.guan);
        } else if(push == 1) {
            // 开
            setFinder.setDrawable(R.id.iv_tixing, R.drawable.kai);

        }
        updateOrderTip();
    }

    @Override
    protected void setListener() {
        super.setListener();
        setFinder.find(R.id.iv_kefu).setOnClickListener(this);
        setFinder.find(R.id.rl_tixing).setOnClickListener(this);
        setFinder.find(R.id.rl_fankui).setOnClickListener(this);
        setFinder.find(R.id.rl_fuwu).setOnClickListener(this);
        setFinder.find(R.id.rl_shengming).setOnClickListener(this);
        setFinder.find(R.id.rl_check).setOnClickListener(this);
        setFinder.find(R.id.rl_order).setOnClickListener(this);
        setFinder.find(R.id.rl_address).setOnClickListener(this);
    }

    /**
     * 订单提醒
     */
    private void updateOrderTip() {
        int order_num=sp.getValue(ORDER_NUM, 0);
        if(order_num > 0) {
            if(order_badge == null) {
                order_badge=new BadgeView(this, findViewById(R.id.rl_order));
            }
            order_badge.setText(order_num + "");
            order_badge.setBadgePosition(BadgeView.POSITION_CENTER);
            // badge.setBackgroundResource(R.color.purple);
            order_badge.setBadgeBackgroundColor(getResources().getColor(R.color.pink));
            order_badge.setTextColor(getResources().getColor(R.color.white));
            order_badge.show(true);
        } else {
            if(order_badge != null)
                order_badge.hide();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch(v.getId()) {
            case R.id.iv_kefu:
                showPopupWindow(setFinder.find(R.id.iv_kefu), 1);
                break;
            case R.id.rl_tixing:
                if(push == 0) {
                    push=1;
                } else {
                    push=0;
                }
                MyRequest req=new MyRequest();
                req.authority=UriHelper.REALM_NAME;
                req.path=UriHelper.URL_PUSH;
                req.paramers=generateParams();
                getDataFromTask(context, PUSH, req, push, true, false);
                break;
            case R.id.rl_fankui:
//                FeedbackAgent agent=new FeedbackAgent(context);
//                agent.startFeedbackActivity();
            	showPopupWindow(setFinder.find(R.id.iv_kefu), 1);
                break;
            case R.id.rl_fuwu:
                // 服务条款
            	Intent intent_2=new Intent(context, MyWebViewActivity.class);
            	intent_2.putExtra(PATH, UriHelper.REALM_NAME+UriHelper.SERVICE);
            	intent_2.putExtra("type", 1);
            	startActivity(intent_2);
            	ActivityUtil.runActivityAnim(SettingActivity.this, false);
                break;
            case R.id.rl_shengming:
                // 声明
            	Intent intent_1=new Intent(context, MyWebViewActivity.class);
            	intent_1.putExtra(PATH, UriHelper.REALM_NAME+UriHelper.DISCLAIMER);
            	intent_1.putExtra("type", 2);
            	startActivity(intent_1);
            	ActivityUtil.runActivityAnim(SettingActivity.this, false);
                break;
            case R.id.rl_check:
                UmengUpdateAgent.update(this);
                UmengUpdateAgent.setUpdateAutoPopup(false);
                UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {

                    @Override
                    public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
                        switch(updateStatus) {
                            case 0: // has update
                                UmengUpdateAgent.showUpdateDialog(context, updateInfo);
                                break;
                            case 1: // has no update
                                Toast.makeText(context, "当前为最新版本", Toast.LENGTH_SHORT).show();
                                break;
                            case 2: // none wifi
                                Toast.makeText(context, "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
                                break;
                            case 3: // time out
                                Toast.makeText(context, "超时", Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                });
                break;
            case R.id.rl_order:
                boolean psw=sp.getValue(PASSWORD, false);
                if(psw) {
                    Intent intent=new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null, context, LockPatternActivity.class);
                    // intent.putExtra(
                    // LockPatternActivity.EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN,
                    // new Intent(context, LockPatternActivity.class));

                    startActivityForResult(intent, REQ_ENTER_PATTERN);
                } else {
                    Intent patternIntent=
                        new Intent(LockPatternActivity.ACTION_CREATE_PATTERN, null, context, LockPatternActivity.class);
                    startActivityForResult(patternIntent, REQ_CREATE_PATTERN);
                }
                // if (TextUtils.isEmpty(sp.getValue(PASSWORD, null))) {
                // // 没有设置密码
                // inputPwd();
                // } else {
                // // 已经设置密码
                // if (mSelectDialog == null) {
                // mSelectDialog = new SelectDialog(context) {
                //
                // @Override
                // public void onSelected(int position, String msg) {
                // if (position == 1) {
                // InputPassWordDialog mInputPassWordDialog = new
                // InputPassWordDialog(
                // context);
                // mInputPassWordDialog.setTitle("请输入应用密码");
                // mInputPassWordDialog
                // .setOnCallBack(new CallBack() {
                //
                // @Override
                // public void cancle() {
                //
                // }
                //
                // @Override
                // public void bakeResult(String result) {
                // if (StringsUtil.getMD5Str(
                // result).equals(
                // sp.getValue(PASSWORD,
                // null))) {
                // sp.setValue(PASSWORD, null);
                // Toast.makeText(context,
                // "已经为您删除了密码", 1)
                // .show();
                // MobclickAgent.onEvent(
                // context,
                // "deletePwd");
                // } else {
                // Toast.makeText(context,
                // "输入密码错误!", 1)
                // .show();
                // }
                //
                // }
                // });
                // mInputPassWordDialog.show();
                // } else {
                // inputPwd();
                // }
                //
                // }
                // };
                // mSelectDialog.addItem("修改密码");
                // mSelectDialog.addItem("删除密码");
                // }
                // mSelectDialog.show();
                //
                // }

                break;
            case R.id.rl_address:
                Intent intent=new Intent(context, MyAddressActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    private void inputPwd() {
        // if (input == null) {
        input=new InputPassWordDialog(context);
        input.setOnCallBack(new CallBack() {

            @Override
            public void cancle() {
                isFirstInput=true;
            }

            @Override
            public void bakeResult(String result) {
                if(isFirstInput) {
                    isFirstInput=false;
                    inputPwd();
                    pwd=result;
                } else {
                    isFirstInput=true;
                    if(result.equals(pwd)) {
                        sp.setValue(PASSWORD, StringsUtil.getMD5Str(result));
                        Toast.makeText(context, "密码设置成功，下次启动应用生效", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(context, "两次输入密码不一致，请重新设置", Toast.LENGTH_LONG).show();
                        inputPwd();
                        pwd=null;
                    }
                }

            }
        });
        // }

        if(isFirstInput) {
            input.setTitle(R.string.prompt_input_psd);
        } else {
            input.setTitle(R.string.prompt_input_psd_again);
        }
        input.show();
    }

    /**
     * 得到传递的参数
     * 
     * @return
     * @throws JSONException
     * @throws IOException
     */
    public Map<String, String> generateParams() {
        JSONObject json=new JSONObject();
        TreeMap<String, String> params=new TreeMap<String, String>();
        params.put("app_key", "android");
        params.put("v", "1.0");
        params.put("type", push + "");
        if(sp.getValue(USER_ID, 0) != 0)
            params.put("user_id", sp.getValue(USER_ID, 0) + "");
        if(!"".equals(sp.getValue(SIG, "")))
            params.put("sig", sp.getValue(SIG, ""));
        return params;
    }

    @Override
    public void handle(int tag, Object object) {
        super.handle(tag, object);
        switch(tag) {
            case PUSH:
                if(object != null) {
                    if((Integer)object != -1) {
                        push=(Integer)object;
                        sp.setValue("push", push);
                        if(push == 0) {
                            // 关
                            setFinder.setDrawable(R.id.iv_tixing, R.drawable.guan);
                        } else if(push == 1) {
                            // 开
                            setFinder.setDrawable(R.id.iv_tixing, R.drawable.kai);

                        }
                    }
                }

                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case MY_ORDER:
                updateBottomOrder();
                updateOrderTip();
                break;
            case REQ_CREATE_PATTERN: {
                if(resultCode == RESULT_OK) {
                    char[] pattern=data.getCharArrayExtra(LockPatternActivity.EXTRA_PATTERN);
                    sp.setValue(PASSWORD, true);
                }
                break;
            }// REQ_CREATE_PATTERN
            case REQ_ENTER_PATTERN: {
                /*
                 * NOTE that there are 4 possible result codes!!!
                 */
                switch(resultCode) {
                    case RESULT_OK:
                        // The user passed
                        LogUtil.i(TAG, "RESULT_OK");
                        Intent intent=new Intent(context, MyOrderActivity.class);
                        startActivityForResult(intent, MY_ORDER);
                        break;
                    case RESULT_CANCELED:
                        // The user cancelled the task
                        LogUtil.i(TAG, "RESULT_CANCELED");
                        break;
                    case LockPatternActivity.RESULT_FAILED:
                        // The user failed to enter the pattern
                        LogUtil.i(TAG, "RESULT_FAILED");
                        break;
                    case LockPatternActivity.RESULT_FORGOT_PATTERN:
                        // The user forgot the pattern and invoked your recovery
                        // Activity.
                        LogUtil.i(TAG, "RESULT_FORGOT_PATTERN");
                        break;
                }

                /*
                 * In any case, there's always a key EXTRA_RETRY_COUNT, which holds the number of tries that the user did.
                 */
                int retryCount=data.getIntExtra(LockPatternActivity.EXTRA_RETRY_COUNT, 0);
                LogUtil.i(TAG, "retryCount---" + retryCount);

                break;
            }// REQ_ENTER_PATTERN

        }
    }
}
